package com.baizhi.service.impl;

import com.baizhi.dao.*;
import com.baizhi.entity.*;
import com.baizhi.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class AdminRoleServiceImpl implements AdminRoleService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private AdminRoleDao adminRoleDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleResourceDao roleResourceDao;
    @Autowired
    private ResourceDao resourceDao;

    @Override
    public Set<String> getAllRolesByUsername(String username) {
//        先根据管理员名查询到管理员的id
        Admin admin = adminDao.selectByName(username);
//        在根据id 查询管理员角色表  得到管理员的所有角色id
        List<AdminRole> adminRoleList = adminRoleDao.selectById(admin.getId());
//        根据角色id查询到所有的角色名直接封装到set中
        Set<String> roles = new HashSet<>();
        for (AdminRole adminRole : adminRoleList) {
            Role role = roleDao.selectById(adminRole.getRoleId());
            roles.add(role.getRoleName());
        }
        return roles;
    }

    @Override
    public Set<String> getAllPermissionsByUsername(String username) {
        //        先根据用户名查询当前管理员的所有角色名
        Set<String> allRolesByUsername = getAllRolesByUsername(username);
        Set<String> permissions = new HashSet<>();
        for (String roleName : allRolesByUsername) {
//            根据角色名 查询 角色权限表 得到权限Id
            List<RoleResource> roleResources = roleResourceDao.selectList(roleName);

            for (RoleResource roleResource : roleResources) {

//                根据权限Id 查询权限表得到权限字符串  where resource_type=function

                Resource resource = resourceDao.selectById(roleResource.getResourceId());
                if (resource != null) {
                    permissions.add(resource.getResourcePermission());
                }
            }
        }
        return permissions;
    }
}
